package com.tanhua.common.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.mapper.UserLoginLogsMapper;
import com.tanhua.common.pojo.UserLoginLogs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Ling
 * @Title: null.java
 * @Package com.tanhua.manage.service
 * @Description:
 * @date 2021/9/13 10:55
 */
@Service
@Slf4j
public class UserLoginLogsService {
    @Autowired
    private UserLoginLogsMapper loginLogsMapper;

    public IPage<UserLoginLogs> getLoginLogs(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder) {

        QueryWrapper<UserLoginLogs> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("login_time");
//        wrapper.orderByDesc(sortProp);
//        if (sortOrder.startsWith("asc")){
//            wrapper.orderByAsc(sortProp);
//        }
//        List<UserLoginLogs> userLoginLogs = loginLogsMapper.selectList(wrapper);
        Page<UserLoginLogs> iPage = new Page<>(page, pageSize);


        return loginLogsMapper.selectPage(iPage, wrapper);
    }

    public UserLoginLogs getLatestLoginLog(Long userId) {
        QueryWrapper<UserLoginLogs> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("login_time");
        wrapper.last("limit 1");
        return loginLogsMapper.selectOne(wrapper);
    }

    public Boolean saveLoginLogs(Long userId) {
        try {
            UserLoginLogs userLoginLogs = new UserLoginLogs();
            userLoginLogs.setEquipment("默认设备");
            userLoginLogs.setUserId(userId);
            userLoginLogs.setLocation("默认地址");
            userLoginLogs.setLoginTime(new Date());
            int insert = loginLogsMapper.insert(userLoginLogs);
            return insert > 0;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return false;
    }


}
